<template>
  <div class="employee-role-container base-page-container">
    <el-container style="height: 100%;">
      <el-aside width="179px" style="height: 100%;display: flex;flex-direction: column;">
        <div class="nav">
          <div class="title-box">分类</div>
          <el-input v-model="typeSearch" placeholder="分类查询"/>
        </div>
        <div class="tree-box">
          <el-tree
            :data="departmentTree"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </div>
      </el-aside>
      <el-main style="height: 100%;display: flex;flex-direction: column;">
        <!-- 搜索区域 -->

        <table-search v-model:showMore="showMore">
          <el-form :inline="true" :model="formData" ref="form" class="demo-form-inline">
            <el-form-item prop="cankuName" label="仓库名称">
              <el-select
                v-model="formData.cankuName"
                filterable
                clearable
                placeholder="请选择"
                multiple
              >
                <el-option
                  v-for="item in cankuArr"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="shopName" label="商品名称">
              <el-input
                clearable
                v-model="formData.shopName"
                style="width: 350px"
                placeholder="多项查询时，输入完整商品名称，并用英文逗号隔开"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品条码" prop="shopNumber">
              <el-input
                v-model="formData.shopNumber"
                placeholder="多项查询时，输入完整商品条码，并用英文逗号隔开"
                clearable
                style="width: 350px"
              ></el-input>
            </el-form-item>
            <span v-show="showMore">
              <el-form-item prop="shipperName" label="货主名称">
                <el-select
                  v-model="formData.shipperName"
                  filterable
                  clearable
                  placeholder="请选择"
                  multiple
                >
                  <el-option
                    v-for="item in shipperNameArr"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="kucunName" label="库存属性">
                <el-select
                  v-model="formData.kucunName"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in kucunNameArr"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </span>
            <el-form-item>
              <el-button type="primary">查询</el-button>
              <el-button>重置</el-button>
            </el-form-item>
          </el-form>
        </table-search>

        <div class="bottoms">
          <!-- 操作按钮区域 -->
          <action-buttons
            :buttons="{
              export: { visible: true, order: 4 },
              hide: { visible: true, order: 5 },
              'clear-search': { visible: true, order: 3, label: '清空查询' }
            }"
            :selected-data="selectedRows"
            :need-select-buttons="['delete']"
            :no-confirm-buttons="['clear-search']"
            @export="handleExport"
            @hide="hideKucunNum"
            @clear-search="clearSearch"
          />

          <div class="bottomsRight">
            <div>当前查询商品汇总：共
              <text>5</text>
              件商品，
              <text>500</text>
              库存
            </div>
          </div>
        </div>

        <!-- 表格区域 -->
        <custom-table
          :data="tableData"
          :columns="tableColumns"
          :loading="tableLoading"
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <!-- 状态列的自定义插槽 -->
          <template #is-enable="{ row }">
            <el-tag :type="row.isEnable ? 'success' : 'info'">
              {{ row.isEnable ? '是' : '否' }}
            </el-tag>
          </template>

          <!-- 允许登录列的自定义插槽 -->
          <template #allow-login="{ row }">
            <el-tag :type="row.allowLogin ? 'success' : 'info'">
              {{ row.allowLogin ? '是' : '否' }}
            </el-tag>
          </template>

          <!-- 操作列 -->
          <template #operation="{ row }">
            <theme-button v-if="tablePermissions.view" link @click="handleGoDetail(row, 'view')">详情</theme-button>
          </template>
        </custom-table>
      </el-main>
    </el-container>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formTitle"
      width="1200px"
      destroy-on-close
      @close="resetForm"
      class="employee-form-dialog"
    >
      <el-form
        style="margin-top: 20px;"
        ref="formRef"
        :model="formData2"
        class="detail-form"
      >
        <div class="form-row">
          <el-form-item prop="shopName" label="商品名称">
            <el-input
              clearable
              v-model="formData2.shopName"
              style="width: 350px"
              disabled
              placeholder="多项查询时，输入完整商品名称，并用英文逗号隔开"
            ></el-input>
          </el-form-item>

          <el-form-item prop="guigeName" label="规格名称">
            <el-input
              clearable
              v-model="formData2.guigeName"
              style="width: 350px"
              disabled
              placeholder="多项查询时，输入完整规格名称，并用英文逗号隔开"
            ></el-input>
          </el-form-item>

          <el-form-item prop="cankuName" label="仓库名称">
            <el-input
              clearable
              v-model="formData2.cankuName"
              style="width: 350px"
              disabled
              placeholder="多项查询时，输入完整仓库名称，并用英文逗号隔开"
            ></el-input>
          </el-form-item>

          <el-form-item prop="dingdanType" label="订单类型">
            <el-select
              v-model="formData2.dingdanType"
              filterable
              clearable
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="item in dingdanTypeArr"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary">查询</el-button>
            <el-button>重置</el-button>
          </el-form-item>

        </div>

        <div class="form-row">
          <el-form-item label="运单日期">

            <el-date-picker
              v-model="TimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="" prop="timeType">
            <el-radio-group v-model="formData2.timeType" @change="changeTimeType">
              <el-radio :value="0">近7天</el-radio>
              <el-radio :value="1">近30天</el-radio>
              <el-radio :value="2">近3个月</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div class="form-row">
          <custom-table
            :data="tableData"
            :columns="tableColumn2"
            :loading="tableLoading"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <!-- 状态列的自定义插槽 -->
            <template #is-enable="{ row }">
              <el-tag :type="row.isEnable ? 'success' : 'info'">
                {{ row.isEnable ? '是' : '否' }}
              </el-tag>
            </template>

            <!-- 允许登录列的自定义插槽 -->
            <template #allow-login="{ row }">
              <el-tag :type="row.allowLogin ? 'success' : 'info'">
                {{ row.allowLogin ? '是' : '否' }}
              </el-tag>
            </template>
          </custom-table>
        </div>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
<!--          <el-button type="primary" @click="handleSubmit" v-if="formMode !== 'view'">确认</el-button>-->
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {useTheme} from '@/hooks/useTheme'
import {useRouter} from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";

// 使用主题组合API
const {themeType} = useTheme()
const router = useRouter()

// 是否显示更多查询
const showMore = ref(false)
const multipleSelection = ref([])

// 表单相关数据
const formDialogVisible = ref(false)
const formRef = ref(null)
const formMode = ref('add')
const formTitle = computed(() => {
  const titles = {
    view: '库存变化详情'
  }
  return titles[formMode.value] || '员工信息'
})

// 表单数据
const formData = reactive({
  cankuName: '', // 仓库名称
  shopName: '', // 商品名称
  shopNumber: '', // 商品条码
  shipperName: '', // 货主名称
  kucunName: '', // 库存属性
})

const getPastDate = (days) => {
  const pastDate = new Date();
  pastDate.setDate(pastDate.getDate() - days);

  const year = pastDate.getFullYear();
  const month = String(pastDate.getMonth() + 1).padStart(2, '0');
  const day = String(pastDate.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;  // 返回格式 YYYY-MM-DD
}

const getTodayDate = () => {
  const today = new Date();

  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;  // 返回格式 YYYY-MM-DD
}

const TimeRange = ref([new Date(getPastDate(7)), new Date(getTodayDate())])
// const endTime = ref(getTodayDate())

const formData2 = reactive({
  shopName: '', // 商品名称
  guigeName: '', // 规格名称
  cankuName: '', // 仓库名称
  dingdanType: '', // 订单类型
  startTime: getPastDate(7), // 发生时间开始
  endTime: getTodayDate(), // 发生时间结束
  timeType: 0
})

const getDateRanges = (param) => {
  // 获取当前日期
  const currentDate = new Date();

  // 格式化日期为 YYYY-MM-DD 格式
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  // 近七天
  const sevenDaysAgo = new Date(currentDate);
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
  const sevenDaysRange = [formatDate(sevenDaysAgo), formatDate(currentDate)];

  // 近 30 天
  const thirtyDaysAgo = new Date(currentDate);
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  const thirtyDaysRange = [formatDate(thirtyDaysAgo), formatDate(currentDate)];

  // 近三个月
  const threeMonthsAgo = new Date(currentDate);
  threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
  const threeMonthsRange = [formatDate(threeMonthsAgo), formatDate(currentDate)];

  // 当前日期
  const currentFormattedDate = formatDate(currentDate);

  switch (param) {
    case 0:
      return {
        dateRange: sevenDaysRange
      };
    case 1:
      return {
        dateRange: thirtyDaysRange
      };
    case 2:
      return {
        dateRange: threeMonthsRange
      };
    default:
      return {
        currentDate: currentFormattedDate,
        lastSevenDays: sevenDaysRange,
        lastThirtyDays: thirtyDaysRange,
        lastThreeMonths: threeMonthsRange
      };
  }
}

const changeTimeType = (val) => {
  let data = getDateRanges(val)
  formData2.startTime = data.dateRange[0];
  formData2.endTime = data.dateRange[1];
  TimeRange.value = [new Date(data.dateRange[0]),new Date(data.dateRange[1])]
}

const cankuArr = [
  {
    title: '仓库1', id: 0
  },
  {
    title: '仓库2', id: 1
  },
  {
    title: '仓库3', id: 2
  }
]

const shipperNameArr = [
  {
    title: '货主1', id: 0
  },
  {
    title: '货主2', id: 1
  },
]

const kucunNameArr = [
  {
    title: '正品', id: 0
  },
  {
    title: '次品', id: 1
  },
]

const dingdanTypeArr = [
  {
    title: '采购入库', id: 0
  },
  {
    title: '调拨入库', id: 1
  },
  {
    title: '其他入库', id: 2
  },
  {
    title: '退货入库', id: 3
  },
  {
    title: '越库入库', id: 4
  },
  {
    title: '销售入库', id: 5
  },
  {
    title: '调拨入库', id: 6
  },
  {
    title: '领用出库', id: 7
  },
  {
    title: '其他出库', id: 8
  },
]

// 权限数据
const permissionData = [
  {
    id: 1,
    label: '系统设置',
    children: [
      { id: 11, label: '用户管理' },
      { id: 12, label: '角色管理' },
      { id: 13, label: '权限管理' }
    ]
  },
  {
    id: 2,
    label: '仓库管理',
    children: [
      { id: 21, label: '入库管理' },
      { id: 22, label: '出库管理' },
      { id: 23, label: '库存查询' }
    ]
  },
  {
    id: 3,
    label: '报表管理',
    children: [
      { id: 31, label: '入库报表' },
      { id: 32, label: '出库报表' },
      { id: 33, label: '库存报表' }
    ]
  }
]

// 搜索表单数据
const searchForm = reactive({
  workNo: '',
  username: '',
  mobile: '',
  company: '',
  department: '' // 从树形控件选择
})

// 清空搜索条件
const clearSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchTableData()
}

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 表格加载状态
const tableLoading = ref(false)

// 表格数据
const tableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 分页大小变更事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 页码变更事件
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  tableLoading.value = true

  // 构造查询参数
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...searchForm
  }

  console.log('查询参数:', params)

  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    tableData.value = Array.from({length: pagination.pageSize}).map((_, index) => ({
      shipperName:  `货主${10000 + index}`,
      shopName: `货主${10000 + index}`,
      shopBianhao: `货主${10000 + index}`,
      shopNumber:  `货主${10000 + index}`,
      guige: `货主${10000 + index}`,
      danwei: '个',
      kucunName: `货主${10000 + index}`,
      zongkucun: `货主${10000 + index}`,
      keyongkucun: `货主${10000 + index}`,
      zhanyongkucun: `货主${10000 + index}`,
      dongjiekucun: `货主${10000 + index}`,
      zaitukucun: `货主${10000 + index}`,
      totolweight: `货主${10000 + index}`,
      totolvolumn: `货主${10000 + index}`,
    }))

    tableLoading.value = false
  }, 300)
}

// 选中的行数据
const selectedRows = ref([])

// 表格多选事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  console.log(rows, selectedRows.value, "表格多选---1111")
}

// 编辑/详情按钮事件
const handleGoDetail = (row, type) => {
  formMode.value = type
  resetForm()

  if (type === 'add') {
    formDialogVisible.value = true
  } else {
    fetchFormDetail(row.id)
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(formData, {
    cankuName: '', // 仓库名称
    shopName: '', // 商品名称
    shopNumber: '', // 商品条码
    shipperName: '', // 货主名称
    kucunName: '', // 库存属性
  })
}

// 获取表单详情数据
const fetchFormDetail = async (id) => {
  try {
    // 这里应该调用接口获取详情
    // 示例使用模拟数据
    tableLoading.value = true
    setTimeout(() => {
      // 通过ID查找对应行数据
      const row = tableData.value.find(item => item.id === id) || {
        id,
        workNo: `工号${id}`,
        username: `小${id}`,
        mobile: `15566009999`,
        email: `user${id}@example.com`,
        company: '公司A',
        department: 'A部门',
        role: '系统管理员',
        isEnable: true,
        allowLogin: true,
        remark: ''
      }

      // 更新表单数据
      Object.assign(formData, {
        id: row.id,
        workNo: row.workNo,
        username: row.username,
        mobile: row.mobile,
        email: row.email,
        company: row.company,
        department: row.department,
        role: row.role,
        isEnable: row.isEnable,
        allowLogin: row.allowLogin,
        remark: row.remark
      })

      formDialogVisible.value = true
      tableLoading.value = false
    }, 300)
  } catch (error) {
    console.error('获取详情失败', error)
    ElMessage.error('获取详情数据失败')
    tableLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  console.log(TimeRange.value, "handleSubmit---111")
  // if (formMode.value === 'view') {
  //   formDialogVisible.value = false
  //   return
  // }
  //
  // try {
  //   // 表单验证
  //   await formRef.value.validate()
  //
  //
  // } catch (error) {
  //   console.error('提交失败', error)
  // }
}

// 表格操作权限 - 默认权限设置
const tablePermissions = reactive({
  edit: true,
  view: true
})

// 表格列配置
const tableColumns = [
  {prop: 'shipperName', label: '货主', width: 120, minWidth: '120', visible: true},
  {prop: 'shopName', label: '商品名称', width: 120, minWidth: '120', visible: true},
  {prop: 'shopBianhao', label: '商品编号', width: 120, minWidth: '120', visible: true},
  {prop: 'shopNumber', label: '商品条码', width: 120, minWidth: '120', visible: true},
  {prop: 'guige', label: '规格', width: 120, minWidth: '120', visible: true},
  {prop: 'danwei', label: '单位', width: 120, minWidth: '120', visible: true},
  {prop: 'kucunName', label: '库存属性', width: 120, minWidth: '120', visible: true},
  {prop: 'zongkucun', label: '总库存', width: 120, minWidth: '120', visible: true},
  {prop: 'keyongkucun', label: '可用库存', width: 120, minWidth: '120', visible: true},
  {prop: 'zhanyongkucun', label: '占用库存', width: 120, minWidth: '120', visible: true},
  {prop: 'dongjiekucun', label: '冻结库存', width: 120, minWidth: '120', visible: true},
  {prop: 'zaitukucun', label: '在途库存', width: 120, minWidth: '120', visible: true},
  {prop: 'totolweight', label: '总重量', width: 120, minWidth: '120', visible: true},
  {prop: 'totolvolumn', label: '总体积', width: 120, minWidth: '120', visible: true},
  {prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true}
]

const tableColumn2 = [
  {prop: 'shipperName', label: '单据类型', width: 120, minWidth: '120', visible: true},
  {prop: 'shopName', label: '发生时间', width: 120, minWidth: '120', visible: true},
  {prop: 'shopBianhao', label: '单据编号', width: 120, minWidth: '120', visible: true},
  {prop: 'shopNumber', label: '仓库', width: 120, minWidth: '120', visible: true},
  {prop: 'guige', label: '发生数量', width: 120, minWidth: '120', visible: true},
  {prop: 'danwei', label: '库存余量', width: 120, minWidth: '120', visible: true},
  {prop: 'kucunName', label: '操作人', width: 120, minWidth: '120', visible: true}
]

// 部门查询
const typeSearch = ref('')

// 部门树数据
const departmentTree = [
  {
    label: 'A部门',
    children: [
      {
        label: 'A-1部门',
      },
      {
        label: 'A-2部门',
      }
    ],
  },
  {
    label: 'B部门',
    children: [
      {
        label: 'B-1部门',
      },
      {
        label: 'B-2部门',
      }
    ],
  },
  {
    label: 'C部门',
    children: [
      {
        label: 'C-1部门',
      },
      {
        label: 'C-2部门',
      }
    ],
  }
]

const defaultProps = {
  children: 'children',
  label: 'label',
}

const handleNodeClick = (data) => {
  console.log(data)
  // 选中部门后，设置查询条件中的部门值
  searchForm.department = data.label
  fetchTableData()
}

// 页面初始化
onMounted(async () => {
  fetchTableData()
})

// 删除按钮事件
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个员工')
    return
  }

  ElMessageBox.confirm('确定要删除选中的员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用接口删除数据
    setTimeout(() => {
      ElMessage.success('删除成功')
      fetchTableData()
    }, 300)
  }).catch(() => {})
}

// 隐藏0库存商品
const hideKucunNum = () => {
  console.log("隐藏0库存商品---hideKucunNum")
}

const handleExport = () => {
  console.log("handleExport--导出")
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的数据!')
    return;
  }

  // 1. 构造 Excel 头部（使用 label）
  const headers = tableColumns.map(col => col.label);

  // 2. 过滤导出数据，仅保留 visible=true 的字段
  const exportData = selectedRows.value.map(row =>
    tableColumns.map(col => row[col.prop] || "") // 提取每列数据
  );

  // 3. 生成 Excel 表格
  const worksheet = XLSX.utils.aoa_to_sheet([headers, ...exportData]);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "导出数据");

  // 4. 生成 Excel 文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
  saveAs(blob, "导出数据.xlsx");
}
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
.employee-role-container {
  padding-left: 0;
  padding-top: 0;
}

.el-aside {
  .nav {
    display: flex;
    flex-direction: column;
    align-items: center;

    .title-box {
      width: 179px;
      height: 42px;
      background: #F0F6FF;
      padding: 10px 20px;
      box-sizing: border-box;
      font-weight: 400;
      font-size: var(--el-font-size-base);
      color: #000000;
    }

    .el-input {
      width: 150px;
      margin: 10px 0;
    }

    :deep(.el-input__wrapper) {
      text-align: center;
      border-radius: 30px;
    }
  }

  .tree-box {
    padding: 0 5px;
    flex: 1;
    overflow: auto;
  }
}

.el-main {
  padding-top: 20px;
  padding-left: 5px;
}

.employee-form-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    text-align: center;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.el-dialog__body) {
    padding: 20px 40px;
  }

  :deep(.el-dialog__footer) {
    padding: 10px 0 20px;
    border-top: 1px solid #f0f0f0;
  }
}

.detail-form {
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    .el-form-item {
      flex: 1;
      min-width: 0;
      margin-bottom: 0;
    }

    .full-width {
      flex: 2;
      width: 100%;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 10px;
}

.bottoms {
  display: flex;
  .bottomsRight {
    margin-left: 20px;
    //height: 50px;
    line-height: 30px;
    text {
      color: orange;
    }
  }
}
</style>
